﻿Imports System.Collections.ObjectModel
Imports System.Collections.Specialized

Public Class ObservableTransform(Of S, D)
    Implements IEnumerable(Of D)
    Implements INotifyCollectionChanged


    Dim _Source As ObservableCollection(Of S)
    Dim _Transform As System.Func(Of S, D)

    Sub New(ByVal source As ObservableCollection(Of S), ByVal trans As Func(Of S, D))
        Me._Source = source
        Me._Transform = trans

        AddHandler source.CollectionChanged, AddressOf SourceCollectionChanged
    End Sub

    Private Function GetEnumerator0() As System.Collections.Generic.IEnumerator(Of D) Implements System.Collections.Generic.IEnumerable(Of D).GetEnumerator
        Return (From e In _Source Select _Transform(e)).GetEnumerator()
    End Function
    Private Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
        Return (From e In _Source Select _Transform(e)).GetEnumerator()
    End Function

    Private Event CollectionChanged(ByVal sender As Object, ByVal e As System.Collections.Specialized.NotifyCollectionChangedEventArgs) Implements System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged

    Private Sub SourceCollectionChanged(ByVal sender As Object, ByVal e As NotifyCollectionChangedEventArgs)
        Select Case e.Action
            Case NotifyCollectionChangedAction.Add
                RaiseEvent CollectionChanged(Me, New NotifyCollectionChangedEventArgs(e.Action, _Transform(e.NewItems(0))))
            Case NotifyCollectionChangedAction.Remove
                RaiseEvent CollectionChanged(Me, New NotifyCollectionChangedEventArgs(e.Action, _Transform(e.OldItems(0))))
            Case NotifyCollectionChangedAction.Reset
                RaiseEvent CollectionChanged(Me, New NotifyCollectionChangedEventArgs(e.Action, e.OldItems))

        End Select

   
    End Sub

End Class